﻿using DataModels.Dto;
using DataModels.Dto.Livelihood;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.Livelihood;
using DataModels.Entities.ServiceDay;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Services.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Services.Livelihood
{
    public class ScoreActivityService(SqlSugarClient db, ProjectService projectService) : BaseService(db)
    {
        readonly ProjectService _projectService=projectService;
        /// <summary>
        /// 获取积分和花费的积分
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetPointsAndExpenses(Guid? projectid = null)
        {
            var customer = db.Queryable<Customer>().Where(c => c.UUID == UserUUID).First();
            if (customer == null)
            {
                return Error("用户不存在");
            }
            int Points = 0; int ConsumePoints = 0;
            if (projectid == null)
            {
                Points = db.Queryable<ServiceDayPoints>()
                   .Where(s => s.UserUUID == UserUUID)
                   .Sum(s => s.Points);
                ConsumePoints = db.Queryable<Customer>()
                    .LeftJoin<LivelihoodActivityPoints>((c, l) => c.UUID.ToString() == l.CustomerUUID)
                    .Where((c, l) => c.UUID == UserUUID)
                    .Sum((c, l) => l.ConsumePoints);

                return Success(new { Points, ConsumePoints });
            }
            int g1 = Convert.ToInt32(GetOrganIdBySIGE((Guid)projectid));
            Points = db.Queryable<Customer>()
               .LeftJoin<ServiceDayPoints>((c, l) => c.UUID == l.UserUUID)
               .Where((c, l) => c.Tel1 == customer.Tel1 && c.OrganId == g1)
               .Sum((c, l) => l.Points);
            ConsumePoints = db.Queryable<Customer>()
               .LeftJoin<LivelihoodActivityPoints>((c, l) => c.UUID.ToString() == l.CustomerUUID)
               .Where((c, l) => c.Tel1 == customer.Tel1 && c.OrganId == g1)
               .Sum((c, l) => l.ConsumePoints);
            return Success(new { Points, ConsumePoints });
        }

        /// <summary>
        /// 获取积分活动
        /// </summary>
        /// <param name="pageRequst"></param>
        /// <returns></returns>
        public ResponseModel GetScoreActivityPage([FromBody] ScoreActivityPageRequest pageRequst)
        {
            //查询当前用户关联的房屋信息
            int sigeid = GetCustIdBySIGE();
            var data = db.Queryable<CustomerHouseRelation>().Where(x => x.CustId == sigeid).ToList();
            var projectIds = new List<string>();
            if (data.Count > 0)
            {
                projectIds = [.. data.Select(x => x.OrganId).Distinct()];
            }
            var project = db.Queryable<Projects>().WhereIF(projectIds.Count > 0, x => projectIds.Contains(x.CommunityId)).First();
            if (project == null) {
                return Error("用户存或项目为空");
            }
            string projectId = project.UUID.ToString();
            var total = 0;
            var res = db.Queryable<LivelihoodScoreActivity>()
                .LeftJoin<Projects>((lc, pj) => lc.ProjectsUUID == Convert.ToString(pj.UUID))
                .Where((lc, pj) => lc.ProjectsUUID == projectId)
                .Where((lc, pj) => lc.IsDeleted == 0)//没有被逻辑删除
                .Where((lc, pj) => lc.State == 1)//上架状态
                .OrderByIF(pageRequst.IsNewest == 0, (lc, pj) => lc.Score)//如果是普通全部，就按照活动花费排序,如果不是就按照活动时间排序
                .OrderByDescending((lc, pj) => lc.CreateTime)
                .Select((lc, pj) => new
                {
                    lc.UUID,
                    lc.ProjectsUUID,
                    pj.ProjectName,
                    lc.Title,
                    lc.Number,
                    lc.Score,
                    lc.State,
                    lc.ImagePathS,
                    lc.PDFPath,
                    lc.CreateTime
                }).ToPageList(pageRequst.PageNumber, pageRequst.PageSize, ref total);
            //重新映射
            var list = res.Select(item => new
            {
                item.UUID,
                item.ProjectsUUID,
                item.ProjectName,
                item.Title,
                item.Number,
                item.Score,
                item.State,
                ImagePathS = !string.IsNullOrEmpty(item.ImagePathS)
            ? item.ImagePathS.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList() //切割数据
            : new List<string>(),
                PDFPath = !string.IsNullOrEmpty(item.PDFPath)
            ? item.PDFPath.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList() //切割数据
            : new List<string>(),
                item.CreateTime
            });
            // 关键修改：分割为列表
            return PageSuccess(pageRequst.PageNumber, pageRequst.PageSize, total, list);
        }

        /// <summary>
        /// 兑换商品
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResponseModel UpdataServiceDayPoint(UpdataServiceDayPointRequest request)
        {
            try
            {
                Console.WriteLine("jiushizhelimaduih");
                if (GetCustIdBySIGE() == 0)
                {
                    return Error("用户不存在");
                }
                var activity = db.Queryable<LivelihoodScoreActivity>()
                    .Where(n => n.UUID == request.LivelihoodScoreActivityUUID)
                    .First();

                if (activity == null)
                    return Error("活动不存在或已结束");

                //查询用户积分
                int Points = db.Queryable<ServiceDayPoints>()
               .Where(s => s.UserUUID == UserUUID)
               .Sum(s => s.Points);
                int ConsumePoints = db.Queryable<LivelihoodActivityPoints>()
                    .Where((l) => l.CustomerUUID == UserUUID.ToString())
                    .Sum((l) => l.ConsumePoints);


                // 验证积分是否充足
                if (activity.Score > (Points- ConsumePoints))
                {
                    return Error("积分不足");
                }
                // 扣除积分
                //var updateSuccess = db.Updateable<ServiceDayPoints>()
                //    .SetColumns(n => n.Points == n.Points - activity.Score)
                //    .Where(n => n.UserUUID == UserUUID && n.Points >= activity.Score) // 带条件更新
                //    .ExecuteCommand() > 0;

                //if (!updateSuccess)
                //{
                //    db.RollbackTran();
                //    return Error("积分不足");
                //}

                // 5. 创建消费记录
                var consumeRecord = new LivelihoodActivityPoints
                {
                    UUID = Guid.NewGuid().ToString(),
                    CustomerUUID = UserUUID.ToString(), // 直接使用UUID字符串
                    LivelihoodScoreActivityUUID = activity.UUID,
                    ConsumePoints = activity.Score,
                    CreateTime = DateTime.Now,
                    IsRrant=0
                };
                db.Insertable(consumeRecord).ExecuteCommand();
                return Success();

            }
            catch (Exception ex)
            {
                return Error($"兑换失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 获取消费记录
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetLivelihoodActivityPointst(GetLivelihoodActivityPointstRequst requst)
        {
            Console.WriteLine("jiushizhelimaxiaofei");
            if (GetCustIdBySIGE() == 0)
            {
                return Error("用户不存在");
            }
            int total = 0;
            var res = db.Queryable<LivelihoodActivityPoints>()
                .LeftJoin<LivelihoodScoreActivity>((s, y) => s.LivelihoodScoreActivityUUID == y.UUID)
                .Where((s, y) => s.CustomerUUID == UserUUID.ToString())
                .Select((s, y) => new GetLivelihoodActivityPointstResponse
                {
                    UUID = s.UUID,
                    Title = y.Title,
                    Number = y.Number,
                    ImagePathS = y.ImagePathS,
                    PDFPath = y.PDFPath,
                    CreateTime = s.CreateTime,
                    ConsumePoints = s.ConsumePoints
                }).ToPageList(requst.PageNumber, requst.PageSize, ref total);

            res.AddRange(db.Queryable<ServiceDayPoints>()
                    .Where(n => n.UserUUID == UserUUID)
                    .Select((n) => new GetLivelihoodActivityPointstResponse
                    {
                        UUID = n.UUID.ToString(),
                        Title = n.Source,
                        Number = "",
                        ImagePathS = "",
                        PDFPath = "",
                        CreateTime = Convert.ToDateTime(n.UpdateTime),
                        ConsumePoints = n.Points
                    }).ToPageList(requst.PageNumber, requst.PageSize, ref total));

            res = res.OrderByDescending(wot => wot.CreateTime).ToList();
            return Success(res);
        }

    }
}
